// import * as auth from 'auth-provider'
import React from 'react'
import { Form, Input} from 'antd'
import { useAuth } from 'context/auth-context'
import { LongButton } from 'unauthenticated-app'
import { useAsync } from 'utils/useAsync'

// interface Base {
//   id:number
// }
// interface Advance extends Base {
//   name:string
// }

// const test = (p:Base)=>{}
// // 鸭子类型（duck typing）：面向接口编程，而不是面向对象编程
// const a = {id:1,name:"jack"}
// test(a)

// const apiUrl = process.env.REACT_APP_API_URL

export default function Register({onError}:{onError:(error:Error)=>void}) {

  // const register = (param:{username:string,password:string} )=>{
  //   fetch(`${apiUrl}/register`,{
  //     method:'POST',
  //     headers:{"Content-Type":"application/json"},
  //     body:JSON.stringify(param)
  //   }).then(
  //    async (response:Response) => {
  //     if(response.ok){
        
  //     }
  //    }
  //   )
  // }

  const {register}=useAuth()
  const {run,isLoading} = useAsync(undefined,{throwOnError:true})

  // HTMLFormElement extends Element
  const handleSubmit = async ({cpassword,...valuse}:{username:string,password:string,cpassword:String}) =>{
    if(cpassword !== valuse.password){
      onError(new Error("请确认两次输入的密码相同"))
      return
    }else{
       run(register(valuse).catch(onError))
    }
  }


  return (
    <div>
      <Form onFinish={handleSubmit}>
        <Form.Item name={'username'} rules={[{required:true,message:"请输入用户名"}]}>
          <Input placeholder={'用户名'} type='text' id={'username'}></Input>
        </Form.Item>
        
        <Form.Item name={'password'} rules={[{required:true,message:"请输入密码"}]}>
          <Input placeholder={'密码'} type='password' id={'password'}></Input>
        </Form.Item>
        <Form.Item name={'cpassword'} rules={[{required:true,message:"请确认密码"}]}>
          <Input placeholder={'确认密码'} type='password' id={'password'}></Input>
        </Form.Item>
        
        <Form.Item>
          <LongButton loading={isLoading} htmlType={'submit'} type={"primary"}>注册</LongButton>
        </Form.Item>
      </Form>
    </div>
  )
}
